<!-- statusBar -->
<template>
  <div class="status-bar">
    <div class="status-bar-wrapper"></div>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
import { envServer as env } from 'anov-core'
import { languageServer as language } from 'anov-core'
import StatusBar from './index.js'
import NetworkStatus from './comp/networkStatus.js'
import Terminal from './comp/terminal.js'
import UpDown from './comp/upDown.js'
import bus from '@/assets/js/app/cmlpanel/util/bus.js'
import appStore from '@/store'
export default {
  name: 'statusBar',
  components: {},
  data() {
    return {
      dataList: [],
      statusMenuFlag: false,
      networkInfo: [{ name: '网速', value: '' }],
      performanceFpsInfo: [{ name: 'FPS', value: 0 }],
      browser: [{ name: '浏览器版本', value: 0 }],
      displayInfo: [
        { name: '分辨率', value: '' },
        { name: '设计尺寸', value: '' },
        { name: '显示效果', value: '' }
      ],
      current: '',

      statusBar: '',
      networkStatus: '',
      statusBarDom: '.status-bar-wrapper',
      upDownType: 0,
      errorTimes: 0,
      terminalInfo: {},
      isWsClosed: true
    }
  },
  computed: {
    ...env.mapState([
      'resolution',
      'browserInfo',
      'resolution',
      'scaleRatio',
      'wrapperSize',
      'designSize',
      'localNetwork',
      'fps',
      'displayEffect',
      'hardware',
      'memory',
      'isConnectCapacityServer',
      'customer',
      'chip',
      'videoIsAvailable',
      'audioIsAvailable'
    ]),
    ...mapState('cmlpanel', ['isFooterNavOpen', 'isPanelOpen']),
    ...language.mapState(['lang']),
    isUpdate() {
      return this.isFooterNavOpen || this.isPanelOpen
    },
    videoStatus() {
      if(app.gestureRecognizeServer.config){
        if (
          !app.gestureRecognizeServer.isStart &&
          !app.lightSensorServer.isStart
        ) {
          this.setVideoStatus(false)
          return false
        } else {
          this.setVideoStatus(true)
          return true
        }
      }
    },
    audioStatus() {
      if(app.gestureRecognizeServer.config){
        if (!app.voiceRecognizeServer.isStart) {
          this.setAudioStatus(false)
          return false
        } else {
          this.setAudioStatus(true)
          return true
        }
      }
    }
  },
  watch: {
    isPanelOpen: {
      handler: function (v) {
        v && this.init()
      }
    },
    isFooterNavOpen: {
      handler: function (v) {
        v && this.init()
      }
    },
    localNetwork: {
      handler: function (v) {
        this.getNetworkInfo()
        this.isUpdate &&
          this.networkStatus.updateItem('network', {
            ...v,
            popupList: this.getNetworkPopupList()
          })
      }
    },
    fps: {
      handler: function () {
        this.getPerformanceFpsInfo()
        this.isUpdate &&
          this.statusBar.updateItem('performanceFps', {
            value: this.fps,
            level: this.getFpsLevel(),
            popupList: this.getFpsPopupList(),
            popupWidth: '120px'
          })
      }
    },
    scaleRatio: {
      handler: function () {
        this.getDisplayInfo()
        this.isUpdate &&
          this.statusBar.updateItem('display', {
            value: this.displayEffect,
            unit: '%',
            popupList: this.displayInfo,
            level: this.getDisplayLevel()
          })
      }
    },
    memory: {
      handler: function () {
        this.isUpdate &&
          this.statusBar.updateItem('memory', {
            value: this.memory.currentMemory.mb,
            unit: this.memory.currentMemory.unit,
            popupList: this.getMemoryPopupList()
          })
      }
    },
    isConnectCapacityServer: {
      handler: function (v1, v2) {
        this.isUpdate && this.getTerminal()
        //增加终端连接信息
        this.isUpdate &&
          this.terminalClass.updateItem('terminal', {
            value: 0,
            status: this.isConnectCapacityServer ? '' : 'undetected'
          })
      }
    },
    audioStatus: {
      handler: function () {
        this.updateAudio()
      }
    },
    audioIsAvailable: {
      handler: function () {
       this.updateAudio()
      }
    },
    videoStatus: {
      handler: function () {
        this.updateVideo()
      }
    },
    videoIsAvailable: {
      handler: function () {
        this.updateVideo()

      }
    },
    lang: {
      handler: function () {
        this.isUpdate &&
          this.statusBar.updateItem('language', {
            value: this.lang.split('-')[1]
          })
      }
    }
  },
  methods: {
    ...env.mapMutations(['setVideoStatus', 'setAudioStatus']),
    init() {
      this.statusBar && this.statusBar.destory()

      this.getDisplayInfo()
      //初始化终端信息
      // this.getTerminal()

      //增加终端连接信息
      let list = {
        apps: [],
        pads: []
      }
      let length = 0
      if(this.terminalInfo.apps){
        length +=this.terminalInfo.apps.length
        list.apps = this.terminalInfo.apps
      }
      if(this.terminalInfo.pads){
        length +=this.terminalInfo.pads.length
        list.pads = this.terminalInfo.pads
      }
      this.terminalClass.addItem({
        key: 'terminal',
        icon: 'iconicon_pingban',
        value: length || 0,
        status: this.isConnectCapacityServer ? '' : 'undetected',
        popupList: list
      })
      // 增加上传下载
      this.upDownClass.addItem({
        key: 'upDown',
        value: this.upDownType,
        popupList: [{ name: '', value: this.upDownType }]
      })

      //增加延时信息
      let value = this.isConnectCapacityServer ? 0 : '-'
      this.statusBar.addItem({
        key: 'delay',
        icon: 'iconicon_yanshi',
        value: value,
        unit: 'ms',
        status: this.isConnectCapacityServer ? '' : 'undetected',
        popupList: this.getDelayPopupList(value, 'ms')
      })

      //增加memory信息
      this.statusBar.addItem({
        key: 'memory',
        icon: 'iconicon_neicun',
        value: this.memory.currentMemory.mb,
        unit: this.memory.currentMemory.unit,
        popupList: this.getMemoryPopupList()
      })

      //增加fps信息
      this.statusBar.addItem({
        key: 'performanceFps',
        icon: 'icon_fps',
        value: this.fps,
        level: this.getFpsLevel(),
        popupList: this.getFpsPopupList()
      })

      //增加网速信息
      this.networkStatus.addItem({
        key: 'network',
        ...this.localNetwork,
        popupList: this.getNetworkPopupList()
      })

      //增加显示效果信息
      this.statusBar.addItem({
        key: 'display',
        icon: 'iconicon_xianshixiaoguo',
        value: this.displayEffect,
        unit: '%',
        popupList: this.displayInfo,
        level: this.getDisplayLevel()
      })

      //增加摄像头信息
      this.statusBar.addItem({
        key: 'video',
        icon: 'iconicon_shexiangtou',
        status: this.videoIsAvailable ? (this.videoStatus ? '' : 'undetected') : 'abnormal',
        popupList: this.getVideoPopupList()
      })

      //增加麦克风信息
      this.statusBar.addItem({
        key: 'audio',
        icon: 'iconicon_maikefeng',
        status: this.audioIsAvailable ? (this.audioStatus ? '' : 'undetected') : 'abnormal',
        popupList: this.getAudioPopupList()
      })

      //增加gpu信息
      this.statusBar.addItem({
        key: 'gpu',
        icon: 'iconicon_gpu',
        value: this.hardware.GPUInfo?.name,
        popupList: this.gpuInfo(),
        popupWidth: '250px'
      })

      //增加浏览器信息
      this.statusBar.addItem({
        key: 'browser',
        icon: this.computedBrowserIcon(),
        value: this.browserInfo.version.split('.')[0],
        popupList: this.getBrowserInfo(),
        popupWidth: '220px'
      })

      // 增加大屏等级信息
      this.statusBar.addItem({
        key: 'level',
        icon: '',
        value: __ANOV__ENV.level,
        popupList: this.getLevelPopupList()
      })

      // 增加所在地信息
      this.statusBar.addItem({
        key: 'address',
        icon: '',
        value: this.customer.info.address || app.config.env.city,
        popupList: this.getAddressPopupList()
      })

      // 增加芯片来源信息
      let icon = ''
      if (this.chip == 'local') {
        icon = 'iconbendixinpian'
      } else {
        icon = 'iconyuanchengxinpian'
      }
      this.statusBar.addItem({
        key: 'chip',
        icon: icon,
        value: ''
      })

      // 增加语言信息
      this.statusBar.addItem({
        key: 'language',
        icon: '',
        value: this.lang.split('-')[1],
        popupList: this.getLangPopupList()
      })
    },
    computedBrowserIcon() {
      let browserName = this.browserInfo.browser.toLowerCase()
      let browserList = ['chrome', 'firefox', 'qqbrowser', 'sogou', 'safari']
      let icon = ''
      browserList.forEach((v, i) => {
        if (browserName.indexOf(v.toLowerCase()) > -1) {
          icon = 'icon_' + v
        }
      })
      return icon
    },
    itemClick(str) {
      this.current = str
      // this.statusBar.updateItem('language',{value: '测试'})
    },
    itemMouseLeave() {
      this.current = ''
    },
    getBrowserInfo() {
      let browser = [
        { name: '浏览器类型', value: this.browserInfo.browser },
        { name: '操作系统', value: this.browserInfo.os },
        { name: '浏览器内核', value: this.browserInfo.engine },
        { name: '浏览器版本', value: this.browserInfo.version }
      ]
      return browser
    },
    getDisplayInfo() {
      this.displayInfo[0].value = this.resolution.w + '*' + this.resolution.h
      this.displayInfo[1].value = this.designSize.w + '*' + this.designSize.h
      this.displayInfo[2].value = this.displayEffect + '%'
    },
    getNetworkInfo() {
      this.networkInfo[0].value =
        this.localNetwork.speed +
        ' ' +
        (this.localNetwork.unit ? this.localNetwork.unit : '')
    },
    getPerformanceFpsInfo() {
      this.performanceFpsInfo[0].value = this.fps
    },
    getTerminal() {
      let msg = { ...this.terminalInfo }
      if (msg) {
        const { type, apps, pads } = msg
        switch (type) {
          case 'disconnect':
            app.msg({
              type: 'info',
              content: this.$t('cmlpanel.remoteDeviceClose')
            })
            this.updateTerminal(apps, pads)
            break
          case 'connected':
            app.msg({
              type: 'info',
              content: this.$t('cmlpanel.remoteDeviceOpen')
            })
            setTimeout(() => {
              app.actionServer.exec('hideqr')
            }, 1000)
            this.updateTerminal(apps, pads)
            break
          case 'close':
            app.msg({ type: 'info', content: this.$t('cmlpanel.remoteClose') })
            app.voiceFeedbackServer.speak('远程控制已关闭')
            break
          case 'open':
            app.msg({ type: 'info', content: this.$t('cmlpanel.remoteOpen') })
            app.voiceFeedbackServer.speak('远程控制已开启')
            break
        }
      }

      // 2021-12-21 此接口暂时废弃 改为 ws调用
      // app.adminServer.getTerminalInfo(
      //   { key: __ANOV__ENV.projectId, code: appStore.state.bigScreenInfo.code },
      //   res => {
      //     if (res && res.code === 200) {
      //       let obj = res.data,
      //         num = 0
      //       for (let i in obj) {
      //         num += obj[i].length
      //       }
      //       //增加终端信息
      //       // if(this.isFooterNavOpen && this.isPanelOpen){
      //       // if(msg){
      //       //   console.log('update',num)
      //       this.terminalClass.updateItem('terminal', {
      //         value: num,
      //         popupList: res.data
      //       })
      //       // }else {
      //       //   this.terminalClass.addItem({key: 'terminal', icon: 'iconicon_pingban', value: num, popupList: res.data})
      //       // }
      //     }
      //   }
      // )
    },
    updateTerminal(apps, pads) {
      let list = {
        apps,
        pads
      }
      this.terminalClass.updateItem('terminal', {
        status: this.isConnectCapacityServer ? '' : 'undetected',
        value: apps.length + pads?.length || 0,
        popupList: list
      })
    },
    gpuInfo() {
      let params = this.hardware.GPUInfo,
        arr = []
      for (let item in params) {
        if (item == 'names') continue
        if (!params[item]) continue
        let obj = {}
        obj.name = item
        obj.value = params[item]
        arr.push(obj)
      }
      return arr
    },
    //计算fps 等级
    getFpsLevel() {
      let arr = app.config.env.fpsLevel,
        level = 0
      for (let i = 0; i < arr.length; i++) {
        if (this.fps < arr[i].fps) {
          level = arr[i].level
          break
        }
        if (this.fps > arr[arr.length - 1].fps) {
          level = arr[arr.length - 1].level
        }
      }
      return level
    },
    getDelayLevel(value) {
      let level = 1
      //delay等级
      let arr = app.config.env ? app.config.env.delayLevel : []
      for (let i = 0; i < arr.length; i++) {
        if (value < arr[i].delay) {
          level = arr[i].level
          break
        }
      }
      return level
    },
    getDisplayLevel() {
      let arr = app.config.env.displayEffectLevel,
        level = 0
      for (let i = 0; i < arr.length; i++) {
        if (this.displayEffect < arr[i].num) {
          level = arr[i].level
          break
        }
        if (this.displayEffect >= arr[arr.length - 1].num) {
          level = arr[arr.length - 1].level
        }
      }
      return level
    },
    //获取地址弹框信息
    getAddressPopupList() {
      let address = [
        {
          name: '地址',
          value: this.customer.info.address || app.config.env.city
        },
        { name: 'ip', value: this.customer.info.ip || '127.0.0.1' }
      ]
      return address
    },
    //获取大屏等级弹框信息
    getLevelPopupList() {
      let level = [{ name: '大屏等级', value: __ANOV__ENV.level }]
      return level
    },
    //获取麦克风弹框信息
    getAudioPopupList() {
      let audio = [
        { name: '麦克风', value: this.audioIsAvailable ? (this.audioStatus ? '已启动' : '未启动') : '不可用' }
      ]
      return audio
    },
    //获取摄像头弹框信息
    getVideoPopupList() {
      let video = [
        { name: '摄像头', value: this.videoIsAvailable ? (this.videoStatus ? '已启动' : '未启动') : '不可用' }
      ]
      return video
    },
    getFpsPopupList() {
      let fps = [{ name: 'fps', value: this.fps }]
      return fps
    },
    getMemoryPopupList() {
      let memory = [
        {
          name: '内存占用',
          value: this.memory.currentMemory.mb + this.memory.currentMemory.unit
        }
      ]
      return memory
    },
    getDelayPopupList(value, unit) {
      let delay = [{ name: '延时', value: value + unit }]
      return delay
    },
    getNetworkPopupList() {
      let network = [
        {
          name: '网速',
          value: this.localNetwork.speed + this.localNetwork.unit
        }
      ]
      return network
    },
    getLangPopupList() {
      let lang = [{ name: '平台语言', value: this.lang }]
      return lang
    },
    updateAudio(){
      this.isUpdate &&
          this.statusBar.updateItem('audio', {
            status: this.audioIsAvailable ? (this.audioStatus ? '' : 'undetected') : 'abnormal',
            popupList: this.getAudioPopupList()
          })
    },
    updateVideo(){
      this.isUpdate &&
          this.statusBar.updateItem('video', {
            status: this.videoIsAvailable ? (this.videoStatus ? '' : 'undetected') : 'abnormal',
            popupList: this.getVideoPopupList()
          })
    }
  },
  created() {},
  mounted() {
    const ws = app.adminServer.ws
    ws?.addEventListener('serverDelay', (e) => {
      let value = 0,
        unit = 'ms',
        level = 0
      if (!isNaN(e)) {
        value = e
        level = this.getDelayLevel(value)
        if (e > 1000) {
          unit = 's'
          value = (e / 1000).toFixed(2)
        }
        this.isUpdate &&
          this.statusBar.updateItem('delay', {
            value: this.isConnectCapacityServer ? value : '-',
            unit: unit,
            status: this.isConnectCapacityServer ? '' : 'undetected',
            level: level,
            popupList: this.getDelayPopupList(value, unit),
            popupWidth: '120px'
          })
      } else {
        value = this.isConnectCapacityServer ? value : '-',
        unit = 'ms'
        this.isUpdate &&
          this.statusBar.updateItem('delay', {
            value: value,
            unit: unit,
            status: this.isConnectCapacityServer ? '' : 'undetected',
            level: level,
            popupList: this.getDelayPopupList(value, unit),
            popupWidth: '120px'
          })
      }
    })
    ws?.addEventListener('wsStatus', (e) => {
      // 0:断开，未连接；1:只有上传；2:只有下载；3:上传和下载
      this.upDownType = e
      this.upDownClass.updateItem('upDown', {
        value: e,
        popupList: [{ name: '', value: this.upDownType }]
      })
    })
    //   this.init();
    this.statusBar = new StatusBar(this.statusBarDom)
    this.networkStatus = new NetworkStatus(this.statusBarDom)
    this.terminalClass = new Terminal(this.statusBarDom)
    this.upDownClass = new UpDown(this.statusBarDom)

    //监听ws返回终端连接状态，调用获取终端信息接口
    ws?.addEventListener('sys', (res) => {
      const { data, apps, pads } = res.data

      if (data === 'quit') {
        this.terminalInfo = { type: 'quit' }
        this.getTerminal({ type: 'quit' })
      } else if (data === 'disconnect') {
        this.terminalInfo = { type: 'disconnect', apps, pads }
        this.getTerminal({ type: 'disconnect', apps, pads })
      } else if (data === 'connected') {
        this.terminalInfo = { type: 'connected', apps, pads }
        this.getTerminal({ type: 'connected', apps, pads })
      }
    })
    ws?.addEventListener('close', (event) => {
      // 重复连接关闭，不再提示
      if (event.code === 4000) {
        app.msg({ type: 'warn', content: '重复连接' })
        return
      }
      if (event.code === 1006) {
        if (this.errorTimes < 1) {
          app.msg({ type: 'info', content: '服务器连接异常' })
        }
        this.errorTimes++
        if (this.errorTimes >= 20) {
          ws.close()
        }
        return
      }
      this.terminalInfo = {type: 'close'}
      if(!this.isWsClosed && event.code === 1000){
        this.getTerminal({ type: 'close' })
      }
      this.isWsClosed = true
    })
    // 连接成功，开始发送数据
    /* ws?.addEventListener('success', (event) => {
      console.log(event)
      this.errorTimes = 0
      this.terminalInfo = {type: 'open'}
      if(this.isWsClosed){
        this.getTerminal({ type: 'open' })
      }
      this.isWsClosed = false
    }) */
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
@import '../../style/panel-var.scss';
@import '../../style/panel-mixin.scss';
@import '../../../../../css/sys-style/panel-var.scss';
.status-bar {
  position: relative;
  width: 100%;
  height: 32px;
  box-sizing: border-box;
  border: 1px solid #293135;
  border-top: none;
  background: #111215;
  .status-bar-wrapper {
    height: 30px;
    @include flex(row, flex-end);
  }
}
</style>
